package com.lvt.design.pattern.module.stat.v2;

import com.google.gson.Gson;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 负责一定频率统计并发送到命令行
 *
 * @author LT
 * @date 2023年02月22日 22:40
 */
public class ConsoleReporter {

    private MetricsStorage metricsStorage;
    private ScheduledExecutorService executorService;

    public ConsoleReporter() {
    }

    public ConsoleReporter(MetricsStorage metricsStorage) {
        this.metricsStorage = metricsStorage;
        this.executorService = Executors.newSingleThreadScheduledExecutor();
    }

    public void startRepeatedReport(long periodInSeconds, long durationInSeconds) {
        executorService.scheduleAtFixedRate(new Runnable() {
            @Override
            public void run() {
               long durationInMills = durationInSeconds * 1000;
               long endTimeInMills = System.currentTimeMillis();
               long startTimInMills = endTimeInMills - durationInMills;
                Map<String, List<RequestInfo>> requestInfos = metricsStorage.getRequestInfos(startTimInMills, endTimeInMills);
                Map<String, RequestStat> stats = new HashMap<>();
                for (Map.Entry<String, List<RequestInfo>> entry : requestInfos.entrySet()) {
                    String apiName = entry.getKey();
                    List<RequestInfo> requestInfosPerApi = entry.getValue();
                    RequestStat requestStat = Aggregator.aggregate(requestInfosPerApi, durationInMills);
                    stats.put(apiName, requestStat);
                }
                System.out.println("Time Span:["+startTimInMills+","+ endTimeInMills+"]");
                Gson gson = new Gson();
                System.out.println(gson.toJson(stats));
            }
        },0, periodInSeconds, TimeUnit.SECONDS);
    }
}
